package xyz.labmem.base.core.tool

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import xyz.labmem.base.core.consts.DATETIME_FORMAT
import xyz.labmem.base.core.consts.DATE_FORMAT
import xyz.labmem.base.core.consts.TIME_FORMAT
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.*

/**
 * @Author lty
 * @Date 2021/12/14 15:26
 */
@Configuration
class JacksonObjectMapper {

    @Bean
    @Primary
    fun serializingObjectMapper(): ObjectMapper {
        val objectMapper = ObjectMapper()

        /*对于LocalDateTime的序列化和反序列化*/
        val dateTimeModule = JavaTimeModule()
        dateTimeModule.addSerializer(
            LocalDateTime::class.java,
            LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT))
        )
        dateTimeModule.addSerializer(
            LocalDate::class.java,
            LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT))
        )
        dateTimeModule.addSerializer(
            LocalTime::class.java,
            LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT))
        )
        dateTimeModule.addDeserializer(
            LocalDateTime::class.java,
            LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT))
        )
        dateTimeModule.addDeserializer(
            LocalDate::class.java,
            LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT))
        )
        dateTimeModule.addDeserializer(
            LocalTime::class.java,
            LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT))
        )
        objectMapper.registerModule(dateTimeModule)

        /*该属性设置主要是取消将对象的时间默认转换timestamp(时间戳)形式*/
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)

        /*该属性设置主要是将忽略空bean转json错误*/
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)

        /*忽略在json字符串中存在，在java类中不存在字段，防止错误*/
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)

        /*设置时间格式的时区*/
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"))
        return objectMapper
    }

}